package com.ext.aic.utils;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityManager;

import androidx.fragment.app.FragmentActivity;

import com.ext.aic.AICApplication;
import com.ext.aic.box.RegisterAccessibilityService;
import com.ext.aic.box.RegisterNotificationService;
import com.ext.aic.box.SettingsHelper;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;
import com.eyinfo.storage.files.FileUtils;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;

public class PermissionUtils {
    private static volatile PermissionUtils instance;

    public static PermissionUtils getInstance() {
        if (instance == null) {
            synchronized (PermissionUtils.class) {
                if (instance == null) {
                    instance = new PermissionUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 打开无障碍设置页面
     *
     * @param tag 自定义标识
     */
    public Intent getAccessibilitySettingsIntent(String tag) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("tag", tag);
        return intent;
    }

    public Intent getRestrictedSettingIntent(String tag) {
        Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("package:" + AICApplication.getInstance().getPackageName()));
        if (tag != null) {
            intent.putExtra("tag", tag);
        }
        return intent;
    }

    public Intent getNotificationSettings(String tag) {
        Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("tag", tag);
        return intent;
    }

    /**
     * 打开应用设置页面
     *
     * @param activity
     * @param requestCode
     * @param tag         自定义标识
     */
    public void startSettings(FragmentActivity activity, int requestCode, String tag) {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            intent.putExtra("tag", tag);
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            // 兼容某些定制 ROM
            Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            intent.putExtra("tag", tag);
            activity.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 打开后台限制设置页面
     *
     * @param activity
     * @param requestCode
     * @param tag         自定义标识
     */
    public void startBackgroundRestrictedSetting(FragmentActivity activity, int requestCode, String tag) {
        try {
            Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            intent.putExtra("tag", tag);
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            // 兼容某些定制 ROM
            startSettings(activity, requestCode, tag);
        }
    }

    /**
     * 打开通知设置页面
     *
     * @param activity
     * @param requestCode
     * @param tag         自定义标识
     */
    public void startNotificationSettings(FragmentActivity activity, int requestCode, String tag) {
        try {
            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("tag", tag);
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            // 兼容某些定制 ROM
            startSettings(activity, requestCode, tag);
        }
    }

    //是否启用无障碍服务
    public boolean isAccessibilityServiceEnabled(Context context) {
        ComponentName componentName = new ComponentName(context, RegisterAccessibilityService.class);
        String serviceName = FileUtils.getExtension(componentName.flattenToString()).trim();
        AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
        for (AccessibilityServiceInfo info : enabledServices) {
            String componentServiceName = FileUtils.getExtension(info.getId()).trim();
            if (TextUtils.equals(componentServiceName, serviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 权限检测，特殊权限该方法不生效（如无障碍权限、通知权限、电池优化）
     *
     * @param activity   FragmentActivity
     * @param permission 权限标识@link Manifest.permission
     * @return true：已授权，false：未授权
     */
    public boolean hasPermission(FragmentActivity activity, String permission) {
        return AndPermission.hasPermissions(activity, permission);
    }

    public boolean isNotificationEnabled(Context context) {
        ComponentName componentName = new ComponentName(context, RegisterNotificationService.class);
        String serviceName = FileUtils.getExtension(componentName.flattenToString()).trim();
        String enabledListeners = Settings.Secure.getString(context.getContentResolver(),
                "enabled_notification_listeners"
        );
        if (enabledListeners == null) {
            return false;
        }
        boolean status = enabledListeners.endsWith(serviceName);
        if (status) {
            return true;
        }
        String[] listeners = enabledListeners.split("/");
        if (ObjectJudge.isNullOrEmpty(listeners)) {
            return false;
        }
        for (String listener : listeners) {
            if (listener.contains(serviceName)) {
                return true;
            }
        }
        return false;
    }

    //检测设备是否处于后台限制状态
    public boolean isBackgroundRestricted(Context context) {
        if (hasBatteryOptimizationSetting(context)) {
            ActivityManager am = context.getSystemService(ActivityManager.class);
            return am != null && am.isBackgroundRestricted();
        } else {
            return false;
        }
    }

    public boolean hasBatteryOptimizationSetting(Context context) {
        Intent intent = getRestrictedSettingIntent(null);
        return intent.resolveActivity(context.getPackageManager()) != null;
    }

    //待后面应用预安装才能实现自启动
    public void autoEnableAccessibility(Context context) {
        if (!isAccessibilityServiceEnabled(context)) {
            String service = "com.ext.aic/com.ext.aic.box.RegisterAccessibilityService";
            SettingsHelper.setAccessibilityService(context, service);
        }
    }
}
